//
//  WKMemberController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/31.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKMemberController.h"
#import "WKNetworkTools.h"
#import "WKDiscountCouponModel.h"
#import "WKLoginHandel.h"
#import "WKUniversal.h"
#import <StoreKit/StoreKit.h>
//沙盒测试环境验证
static NSString *SANDBOX=@"https://sandbox.itunes.apple.com/verifyReceipt";
//正式环境验证
static NSString *AppStore=@"https://buy.itunes.apple.com/verifyReceipt";

@interface WKMemberController ()<SKPaymentTransactionObserver, SKProductsRequestDelegate>

@property (weak, nonatomic) IBOutlet UIButton *btnJunior;
@property (weak, nonatomic) IBOutlet UIButton *btnHigh;
@property (weak, nonatomic) IBOutlet UILabel *btnTip;

@property (weak, nonatomic) IBOutlet UIView *viewPrice;
@property (weak, nonatomic) IBOutlet UIView *viewBottom;
@property (weak, nonatomic) IBOutlet UILabel *labelTotal;

@property (weak, nonatomic) IBOutlet UIButton *btnPay;
@property (weak, nonatomic) IBOutlet UIButton *btnCoupons;//优惠券

@property (weak, nonatomic) IBOutlet UILabel *oneLabel;
@property (weak, nonatomic) IBOutlet UILabel *sixLabel;
@property (weak, nonatomic) IBOutlet UILabel *twelveLabel;
@property (weak, nonatomic) IBOutlet UIButton *btnOne;
@property (weak, nonatomic) IBOutlet UIButton *btnSix;
@property (weak, nonatomic) IBOutlet UIButton *btnTwelve;
//优惠
@property (nonatomic, copy) NSString *price;
@property (nonatomic, copy) NSString *price10;
@property (nonatomic, copy) NSString *price09;
@property (nonatomic, copy) NSString *price08;
@property (nonatomic, copy) NSString *price07;
@property (nonatomic, copy) NSString *price06;
@property (nonatomic, copy) NSString *price05;
@property (nonatomic, copy) NSString *price04;
@property (nonatomic, copy) NSString *price03;
@property (nonatomic, copy) NSString *price02;
@property (nonatomic, copy) NSString *price01;
@property (nonatomic, copy) NSString *product_id;
@property (nonatomic, copy) NSString *product_id10;
@property (nonatomic, copy) NSString *product_id09;
@property (nonatomic, copy) NSString *product_id08;
@property (nonatomic, copy) NSString *product_id07;
@property (nonatomic, copy) NSString *product_id06;
@property (nonatomic, copy) NSString *product_id05;
@property (nonatomic, copy) NSString *product_id04;
@property (nonatomic, copy) NSString *product_id03;
@property (nonatomic, copy) NSString *product_id02;
@property (nonatomic, copy) NSString *product_id01;
@property (weak, nonatomic) IBOutlet UIButton *btnPreferential;
@property (nonatomic, strong) NSMutableArray *sixCouponidArr;
@property (nonatomic, strong) NSMutableArray *twelveCouponidArr;
@property (nonatomic, assign) BOOL isJunior;
@property (nonatomic, assign) BOOL isHigh;
@property (nonatomic, assign) BOOL isSix;
@property (nonatomic, assign) BOOL isTwelve;
@property (nonatomic, copy) NSString *typeid;
@property (nonatomic, copy) NSString *couponid;

@end

@implementation WKMemberController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navItem.title = @"会员中心";
    self.sixCouponidArr = [NSMutableArray array];
    self.twelveCouponidArr = [NSMutableArray array];
    [self loadDiscountCoupon];
    [self loadPriceInfo];
    self.typeid = @"2";
    _isHigh = YES;
    [self setupUI];
    if (_isOpen) {
        if ([self.status isEqualToString:@"1"]) {
            //初中
            [self btnJunior:nil];
        }else if ([self.status isEqualToString:@"2"]){
            //高中
            [self btnHighAction:nil];
        }
    }
}
- (void)setupUI{
    
    self.navgationBar.barTintColor = RGBColor(40, 188, 203);
    
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);
    
    [self middleTitleColor:[UIColor whiteColor]];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#fafafa"];
    self.navItem.leftBarButtonItem = nil;
    [self setLeftButtonWithImage:@"icon_return_white" highlightedImage:@"icon_return_white" target:self action:@selector(backAction)];
    
    self.btnJunior.layer.cornerRadius = 2;
    self.btnJunior.layer.masksToBounds = YES;
    self.btnJunior.layer.borderColor = [UIColor colorWithHexString:@"#2BBBCB"].CGColor;
    self.btnJunior.layer.borderWidth = 0.5;
    self.btnHigh.layer.cornerRadius = 2;
    self.btnHigh.layer.masksToBounds = YES;
    self.btnHigh.layer.borderColor = [UIColor colorWithHexString:@"#2BBBCB"].CGColor;
    self.btnHigh.layer.borderWidth = 0.5;
    
    self.btnOne.layer.cornerRadius = 3;
    self.btnOne.layer.masksToBounds = YES;
    self.btnSix.layer.cornerRadius = 3;
    self.btnSix.layer.masksToBounds = YES;
    self.btnTwelve.layer.cornerRadius = 3;
    self.btnTwelve.layer.masksToBounds = YES;

}
#pragma mark - 获取价格信息
- (void)loadPriceInfo{
    __weak typeof(self) weakSelf = self;
    NSString *phpsessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"getiosvipdetail" forKey:@"commandid"];
    [para setObject:phpsessid forKey:@"phpsessid"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:@"" completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *head = dict[@"head"];
        if ([head[@"statuscode"] intValue] == 100) {
            NSDictionary *body = dict[@"body"];
            NSDictionary *ident10 = body[@"com.dezhi.classroom.WeKeTang10"];
            NSString *price10 = ident10[@"price"];
            NSString *product_id10 = ident10[@"product_id"];
            weakSelf.price10 = price10;
            weakSelf.product_id10 = product_id10;
            NSDictionary *ident09 = body[@"com.dezhi.classroom.WeKeTang09"];
            NSString *price09 = ident09[@"price"];
            NSString *product_id09 = ident09[@"product_id"];
            weakSelf.price09 = price09;
            weakSelf.product_id09 = product_id09;
            NSDictionary *ident08 = body[@"com.dezhi.classroom.WeKeTang08"];
            NSString *price08 = ident08[@"price"];
            NSString *product_id08 = ident08[@"product_id"];
            weakSelf.price08 = price08;
            weakSelf.product_id08 = product_id08;
            NSDictionary *ident07 = body[@"com.dezhi.classroom.WeKeTang07"];
            NSString *price07 = ident07[@"price"];
            NSString *product_id07 = ident07[@"product_id"];
            weakSelf.price07 = price07;
            weakSelf.product_id07 = product_id07;
            NSDictionary *ident06 = body[@"com.dezhi.classroom.WeKeTang06"];
            NSString *price06 = ident06[@"price"];
            NSString *product_id06 = ident06[@"product_id"];
            weakSelf.price06 = price06;
            weakSelf.product_id06 = product_id06;
            NSDictionary *ident05 = body[@"com.dezhi.classroom.WeKeTang05"];
            NSString *price05 = ident05[@"price"];
            NSString *product_id05 = ident05[@"product_id"];
            weakSelf.price05 = price05;
            weakSelf.product_id05 = product_id05;
            NSDictionary *ident04 = body[@"com.dezhi.classroom.WeKeTang04"];
            NSString *price04 = ident04[@"price"];
            NSString *product_id04 = ident04[@"product_id"];
            weakSelf.price04 = price04;
            weakSelf.product_id04 = product_id04;
            NSDictionary *ident03 = body[@"com.dezhi.classroom.WeKeTang03"];
            NSString *price03 = ident03[@"price"];
            NSString *product_id03 = ident03[@"product_id"];
            weakSelf.price03 = price03;
            weakSelf.product_id03 = product_id03;
            NSDictionary *ident02 = body[@"com.dezhi.classroom.WeKeTang02"];
            NSString *price02 = ident02[@"price"];
            NSString *product_id02 = ident02[@"product_id"];
            weakSelf.price02 = price02;
            weakSelf.product_id02 = product_id02;
            NSDictionary *ident01 = body[@"com.dezhi.classroom.WeKeTang01"];
            NSString *price01 = ident01[@"price"];
            NSString *product_id01 = ident01[@"product_id"];
            weakSelf.price01 = price01;
            weakSelf.product_id01 = product_id01;
            weakSelf.oneLabel.text = [NSString stringWithFormat:@"%@元",price06];
            weakSelf.sixLabel.text = [NSString stringWithFormat:@"%@元",price07];
            weakSelf.twelveLabel.text = [NSString stringWithFormat:@"%@元",price09];
        }
        NSLog(@"价格：%@",dict);
    }];
    
}
#pragma mark - 获取优惠券
- (void)loadDiscountCoupon{
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *sessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac = [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"wkcouponlist" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:sessid forKey:@"phpsessid"];
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"获取中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"优惠券接口：%@",dict);
        NSDictionary *headDict = dict[@"head"];
        NSString *statuscode = headDict[@"statuscode"];
        NSArray *bodyList = dict[@"body"];
        NSMutableArray *mArray = [NSMutableArray array];
        NSMutableArray *sixArray = [NSMutableArray array];
        NSMutableArray *sixCouponidArr = [NSMutableArray array];
        NSMutableArray *twelveArray = [NSMutableArray array];
        NSMutableArray *twelveCouponidArr = [NSMutableArray array];
        if ([statuscode intValue] == 100) {
            for (NSInteger i = 0; i<bodyList.count; i++) {
                NSDictionary *dict = bodyList[i];
                if ([dict[@"usestatus"] integerValue] == 0 ) {
                    //拿到可用的优惠券
                    [mArray addObject:dict];
                }
            }
            for (NSInteger i = 0; i<mArray.count; i++) {
                NSDictionary *dict = mArray[i];
                if ([dict[@"coupontype"] integerValue] == 11) {
                    [sixArray addObject:dict];
                    [sixCouponidArr addObject:dict[@"id"]];
                    
                }
            }
            
            for (NSInteger i = 0; i<mArray.count; i++) {
                NSDictionary *dict = mArray[i];
                if ([dict[@"coupontype"] integerValue] == 12) {
                    [twelveArray addObject:dict];
                    [twelveCouponidArr addObject:dict[@"id"]];
                }
            }
            weakSelf.sixCouponidArr = sixCouponidArr;
            weakSelf.twelveCouponidArr = twelveCouponidArr;
            //如果不为0 说明用户有28元优惠券
            if (sixArray.count !=0 ) {
                _isSix = YES;
            }else{
                _isSix = NO;
            }
            //如果不为0 说明用户有50元优惠券
            if (twelveArray.count != 0) {
                _isTwelve = YES;
            }else{
                _isTwelve = NO;
            }
             NSLog(@"优惠券接口：%@",mArray);
            NSLog(@"优惠券接口6：%@",weakSelf.sixCouponidArr);
            NSLog(@"优惠券接口12：%@",weakSelf.twelveCouponidArr);
            NSLog(@"优惠券接口8：%@",weakSelf.sixCouponidArr.lastObject);
        }else if([statuscode intValue] == 999){
           
            NSLog(@"没有优惠券");
        }
    }];
    
}
#pragma mark - 高中会员
- (IBAction)btnHighAction:(UIButton *)sender {
    _isHigh = YES;
    _isJunior = NO;
    self.typeid = @"2";
    [self.btnHigh setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.btnHigh.backgroundColor = [UIColor colorWithHexString:@"#2BBBCB"];
    self.btnJunior.backgroundColor = [UIColor whiteColor];
    [self.btnJunior setTitleColor:[UIColor colorWithHexString:@"#2BBBCB"] forState:UIControlStateNormal];

    self.btnTip.text = @"会员期内可观看高中学段所有课程";
}

#pragma mark - 初中会员
- (IBAction)btnJunior:(UIButton *)sender {
    self.typeid = @"1";
    _isHigh = NO;
    _isJunior = YES;
    [self.btnJunior setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.btnJunior.backgroundColor = [UIColor colorWithHexString:@"#2BBBCB"];
    self.btnHigh.backgroundColor = [UIColor whiteColor];
    [self.btnHigh setTitleColor:[UIColor colorWithHexString:@"#2BBBCB"] forState:UIControlStateNormal];
    self.btnTip.text = @"会员期内可观看初中学段所有课程";
}
#pragma mark -开通1个月
- (IBAction)openOneMemberAction:(UIButton *)sender {
//    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
//    if ([userid isEqualToString:@"1469149"]) {
//        [self showCustomAlertMessage:@"您当前是游客身份,请先注册会员!"];
//        return;
//    }
    //开通1个月没有优惠
    if (_isJunior) {
        [self paymentsWithProductId:self.product_id01];
        self.price = self.price01;
        self.product_id = self.product_id01;
        
    }else if (_isHigh){
        [self paymentsWithProductId:self.product_id06];
        self.price = self.price06;
        self.product_id = self.product_id06;
        
    }
}
#pragma mark - 开通6个月
- (IBAction)openSixMemberAction:(UIButton *)sender {
//    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
//    if ([userid isEqualToString:@"1469149"]) {
//        [self showCustomAlertMessage:@"您当前是游客身份,请先注册会员!"];
//        return;
//    }
    //按钮选中并且用户有优惠券
    if (self.btnPreferential.selected && _isSix == YES) {
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id03];
            self.price = self.price03;
            self.product_id = self.product_id03;
            self.couponid = self.sixCouponidArr.lastObject;
        }else if (_isHigh){
            
            [self paymentsWithProductId:self.product_id08];
            self.price = self.price08;
            self.product_id = self.product_id08;
            self.couponid = self.sixCouponidArr.lastObject;
        }
        NSLog(@"6个月有并且用优惠券");
    }else if (self.btnPreferential.selected && _isSix == NO){
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id02];
            self.price = self.price02;
            self.product_id = self.product_id02;
        }else if (_isHigh){
            
            [self paymentsWithProductId:self.product_id07];
            self.price = self.price07;
            self.product_id = self.product_id07;
        }
        NSLog(@"6个月没有优惠券");
        [self showCustomAlertMessage:@"您没有优惠券,如购买将以原价购买!"];
    }else{
        NSLog(@"6个月不用优惠券");
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id02];
            self.price = self.price02;
            self.product_id = self.product_id02;
        }else if (_isHigh){
            [self paymentsWithProductId:self.product_id07];
            self.price = self.price07;
            self.product_id = self.product_id07;
        }
        
    }
}
#pragma mark - 开通12个月
- (IBAction)openTwelveMemberAction:(UIButton *)sender {
//    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
//    if ([userid isEqualToString:@"1469149"]) {
//        [self showCustomAlertMessage:@"您当前是游客身份,请先注册会员!"];
//        return;
//    }
    //按钮选中并且用户有优惠券
    if (self.btnPreferential.selected && _isTwelve == YES ) {
        NSLog(@"12个月有并且用优惠券");
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id05];
            self.price = self.price05;
            self.product_id = self.product_id05;
            self.couponid = self.twelveCouponidArr.lastObject;
        }else if (_isHigh){
            [self paymentsWithProductId:self.product_id10];
            self.price = self.price10;
            self.product_id = self.product_id10;
            self.couponid = self.twelveCouponidArr.lastObject;
        }
    }else if (self.btnPreferential.selected && _isTwelve == NO){
        
        NSLog(@"12个月没有优惠券");
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id04];
            self.price = self.price04;
            self.product_id = self.product_id04;
            
        }else if (_isHigh){
            [self paymentsWithProductId:self.product_id09];
            self.price = self.price09;
            self.product_id = self.product_id09;
        }
    }else{
        NSLog(@"12个月不用优惠券");
        if (_isJunior) {
            [self paymentsWithProductId:self.product_id04];
            self.price = self.price04;
            self.product_id = self.product_id04;
        }else if (_isHigh){
            [self paymentsWithProductId:self.product_id09];
            self.price = self.price09;
            self.product_id = self.product_id09;
        }
    }
}
#pragma mark - 参与优惠
- (IBAction)btnPreferentialAction:(UIButton *)sender {
    
    sender.selected =! sender.selected;
    
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"icon_memberselect"] forState:UIControlStateNormal];
        [sender setImage:[UIImage imageNamed:@"icon_memberselect"] forState:UIControlStateHighlighted];
        if (_isSix && _isTwelve) {
            self.sixLabel.text = [NSString stringWithFormat:@"%@元",self.price03];
            self.twelveLabel.text = [NSString stringWithFormat:@"%@元",self.price10];
            [self showCustomAlertMessage:@"已为您选择最佳优惠"];
        }else if(_isSix){
            self.sixLabel.text = [NSString stringWithFormat:@"%@元",self.price03];
            self.twelveLabel.text = [NSString stringWithFormat:@"%@元",self.price09];
            [self showCustomAlertMessage:@"已为您选择最佳优惠"];
        }else if (_isTwelve){
             self.sixLabel.text =[NSString stringWithFormat:@"%@元",self.price06] ;
            self.twelveLabel.text =[NSString stringWithFormat:@"%@元",self.price10] ;
            [self showCustomAlertMessage:@"已为您选择最佳优惠"];
        }else{
            self.sixLabel.text = [NSString stringWithFormat:@"%@元",self.price02];
            self.twelveLabel.text = [NSString stringWithFormat:@"%@元",self.price09];
            [self showCustomAlertMessage:@"您暂无优惠券"];
        }
   
    }else{
        [sender setImage:[UIImage imageNamed:@"icon_membernomal"] forState:UIControlStateNormal];
        [sender setImage:[UIImage imageNamed:@"icon_membernomal"] forState:UIControlStateHighlighted];
        self.sixLabel.text = [NSString stringWithFormat:@"%@元",self.price07];
        self.twelveLabel.text = [NSString stringWithFormat:@"%@元",self.price09];
    }
}
//比较时间方法
- (NSInteger)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        return -1;
    }
    //刚好时间一样.
    return 0;
}

#pragma mark - 返回
- (void)backAction{
    
    if (self.memberBlock) {
        self.memberBlock();
    }
    [super backAction];
}
#pragma mark - 支付方法
- (void)paymentsWithProductId:(NSString*)productId{
    [self showIndicatorWithFlag:YES title:@"苹果验证中,请耐心等待..."];
    if([SKPaymentQueue canMakePayments]){
        [self showIndicatorWithFlag:YES title:@"苹果验证中,请耐心等待..."];
        NSSet *nsset = [NSSet setWithObjects:productId, nil];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
        request.delegate = self;
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];  
        [request start];
    }else{
        [self showCustomAlertMessage:@"不允许进行内购"];
    }
}
//接收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *product = response.products;
    if([product count] == 0){
        return;
    }
    NSLog(@"-------%ld",product.count);
    [self showIndicatorWithFlag:YES title:@"苹果验证中,请耐心等待..."];
    NSLog(@"productID:%@", response);
    NSLog(@"产品付费数量:%lu",(unsigned long)[product count]);
    NSLog(@"SKProduct 描述信息%@", [product description]);
    for (SKProduct *pro in product) {
        NSLog(@"SKProduct 描述信息%@", [pro description]);
        NSLog(@"产品标题%@", [pro localizedTitle]);
        NSLog(@"产品描述信息:%@", [pro localizedDescription]);
        NSLog(@"价格:%@", [pro price]);
        NSLog(@"Product id:%@", [pro productIdentifier]);
        SKPayment *payment = [SKPayment paymentWithProduct:pro];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    
    [self showCustomAlertMessage:@"购买错误"];
     [self showIndicatorWithFlag:NO title:nil];
    NSLog(@"request---didFailWithError");
}

- (void)requestDidFinish:(SKRequest *)request {
    [self showIndicatorWithFlag:NO title:nil];
    
    NSLog(@"requestDidFinish");
}
#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    [self showIndicatorWithFlag:YES title:@"苹果验证中,请耐心等待..."];
    
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                NSLog(@"交易完成");
                [self showIndicatorWithFlag:NO title:nil];
                NSLog(@"记录:%@",tran.transactionIdentifier);
            [self verifyPurchaseWithPaymentTransactionWithIdentifier:tran.transactionIdentifier];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                [self showIndicatorWithFlag:NO title:nil];
                break;
            case SKPaymentTransactionStateRestored:{
                
                [self showIndicatorWithFlag:NO title:nil];
                [self showCustomAlertMessage:@"您已经购买过该商品"];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{
                [self showIndicatorWithFlag:NO title:nil];
                [self showCustomAlertMessage:@"购买失败"];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            default:
                break;
        }
    }
}
//交易失败后的操作
-(void)failedTransaction:(SKPaymentTransaction *)transaction{
    
    if (transaction.error.code != SKErrorPaymentCancelled) {
    }else{
    }
    //移除transaction购买操作
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

#pragma mark - 验证服务器
-(void)verifyPurchaseWithPaymentTransactionWithIdentifier:(NSString*)identifier{
    [self showIndicatorWithFlag:YES title:@"验证中,请耐心等待..."];
    if (self.couponid == nil || [self.couponid isEqualToString:@""]||[self.couponid isEqualToString:@"null"]) {
        self.couponid = @"0";
    }
    __weak typeof(self) weakSelf = self;
    NSString* sandbox = @"2";//正式环境
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符
    NSURL *url=[NSURL URLWithString:SANDBOX];
    NSData *bodyData = [receiptString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody=bodyData;
    NSString *receipt = [[NSString alloc]initWithData:requestM.HTTPBody encoding:NSUTF8StringEncoding];
    NSLog(@"------------%@",receipt);
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *sessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac= [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"becomeiosvip" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:sessid forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:self.typeid forKey:@"typeid"];
    [para setObject:self.product_id forKey:@"product_id"];
    [para setObject:self.price forKey:@"price"];
    [para setObject:receipt forKey:@"receipt_data"];
    [para setObject:identifier forKey:@"transaction_id"];
    [para setObject:sandbox forKey:@"sandbox"];
    [para setObject:self.couponid forKey:@"couponid"];
    [para setObject:@"2" forKey:@"request_times"];
    NSLog(@"验证参数:%@",para);
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *headDict = dict[@"head"];
    
        NSString *statuscode = headDict[@"statuscode"];
       
        if ([statuscode intValue ] == 100) {
             [weakSelf showIndicatorWithFlag:NO title:nil];
            [self showCustomAlertMessage:@"购买成功"];
           
        }
        if ([statuscode intValue ] == 21008) {
             [weakSelf showIndicatorWithFlag:NO title:nil];
            [self showCustomAlertMessage:@"验证失败"];
            
        }
        if ([statuscode intValue ] == 21007) {
             [weakSelf showIndicatorWithFlag:NO title:nil];
            [self showCustomAlertMessage:@"再次开启验证"];
            //多次请求服务器
            [weakSelf verifyPurchaseTestServerWithIdentifier:identifier];
        }
       NSLog(@"第一次验证参数:%@",dict);
        
        [self showIndicatorWithFlag:NO title:nil];
    }];

}
#pragma mark - 正式环境失败转达沙箱环境下验证
- (void)verifyPurchaseTestServerWithIdentifier:(NSString*)identifier{
    [self showIndicatorWithFlag:YES title:@"验证中,请耐心等待..."];
    if (self.couponid == nil || [self.couponid isEqualToString:@""]||[self.couponid isEqualToString:@"null"]) {
        self.couponid = @"0";
    }
    __weak typeof(self) weakSelf = self;
    
    NSString* sandbox = @"1";
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符
    NSURL *url=[NSURL URLWithString:SANDBOX];
    NSData *bodyData = [receiptString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody=bodyData;
    NSString *receipt = [[NSString alloc]initWithData:requestM.HTTPBody encoding:NSUTF8StringEncoding];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *sessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac= [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"becomeiosvip" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:sessid forKey:@"phpsessid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:self.typeid forKey:@"typeid"];
    [para setObject:self.product_id forKey:@"product_id"];
    [para setObject:self.price forKey:@"price"];
    [para setObject:receipt forKey:@"receipt_data"];
    [para setObject:identifier forKey:@"transaction_id"];
    [para setObject:sandbox forKey:@"sandbox"];
    
    [para setObject:self.couponid forKey:@"couponid"];
    [para setObject:@"2" forKey:@"request_times"];
    
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:nil completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"第二次验证参数:%@",dict);
        NSDictionary *headDict = dict[@"head"];
        
        NSString *statuscode = headDict[@"statuscode"];
        
        if ([statuscode intValue ] == 100) {
            [weakSelf showIndicatorWithFlag:NO title:nil];
            [weakSelf showCustomAlertMessage:@"验证成功"];
        }
        
    }];
}
- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end
